package com.hz.erp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hz.erp.constant.RetResponse;
import com.hz.erp.constant.RetResult;
import com.hz.erp.dao.UserMapper;
import com.hz.erp.entity.dto.UserDto;
import com.hz.erp.entity.page.PageRequest;
import com.hz.erp.entity.page.PageResult;
import com.hz.erp.entity.vo.UserVo;
import com.hz.erp.enums.commons.DeleteFlagEnum;
import com.hz.erp.enums.commons.ManagementFlagEnum;
import com.hz.erp.enums.commons.RegistrationWayEnum;
import com.hz.erp.service.UserService;
import com.hz.erp.utils.JsonUtil;
import com.hz.erp.utils.MathUtils;
import com.hz.erp.utils.Md5Util;
import com.hz.erp.utils.PageUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 柯鑫
 * @ClassName com.hz.erp.service.impl.UserServiceImpl
 * @description 用户接口服务实现类
 * @create 2020年06月04日 15:58
 */
@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    @Override
    public RetResult<UserVo> selectUserById(Long id) {
        if(id == null){
            return  RetResponse.makeErrRsp("id丢失,您不能查询");
        }
        return RetResponse.makeOKRsp(userMapper.selectUserById(id));
    }

    @Override
    public RetResult<List<UserDto>> selectUserAll(UserVo user) {
        if(user == null){
            return RetResponse.makeErrRsp("注册信息不存在,请检查重新填写");
        }

        if(null == user.getId()){
            return RetResponse.makeErrRsp("请传入id查看!");
        }
        UserVo userOne = userMapper.selectUserById(user.getId());

        //如果是超级管理员， 根据条件查询
        if(ManagementFlagEnum.SUPER_MANAGEMENT.getCode().equals(userOne.getManagementFlag())){

            user.setChildId(null);
        }        //如果是管理员, 根据id,查询所有的子id
        else if(ManagementFlagEnum.IS_MANAGEMENT.getCode().equals(userOne.getManagementFlag())){
            user.setChildId(user.getId());
        }
        else {
         return RetResponse.makeErrRsp("您不是管理员，不能查看!");
        }

        List<UserDto> restUserList = new ArrayList<>();

        for (UserVo userVo : userMapper.selectUserAll(user)) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(userVo, userDto);

            userDto.setDeleteFlag(DeleteFlagEnum.setCodeGetDesc(userVo.getDeleteFlag()));
            userDto.setManagementFlag(ManagementFlagEnum.setCodeGetDesc(userVo.getManagementFlag()));

            restUserList.add(userDto);
        }

        return RetResponse.makeOKRsp(restUserList);
    }

    /**
     * 调用分页插件完成分页
     * @param pageRequest
     * @return
     */
    @Override
    public RetResult<PageResult> findUserListPage(PageRequest pageRequest,  UserVo user) {
        if(user == null){
            return RetResponse.makeErrRsp("注册信息不存在,请检查重新填写");
        }

        if(null == user.getId()){
            return RetResponse.makeErrRsp("请传入id查看!");
        }
        UserVo userOne = userMapper.selectUserById(user.getId());

        //如果是超级管理员， 根据条件查询
        if(ManagementFlagEnum.SUPER_MANAGEMENT.getCode().equals(userOne.getManagementFlag())){

            user.setChildId(null);
        }        //如果是管理员, 根据id,查询所有的子id
        else if(ManagementFlagEnum.IS_MANAGEMENT.getCode().equals(userOne.getManagementFlag())){
            user.setChildId(user.getId());
        }
        else {
            return RetResponse.makeErrRsp("您不是管理员，不能查看!");
        }
        return RetResponse.makeOKRsp(PageUtils.getPageResult(getPageInfo(pageRequest, user)));
    }

    /**
     * 调用分页插件完成分页
     * @param pageRequest
     * @return
     */
    private PageInfo<UserDto> getPageInfo(PageRequest pageRequest,  UserVo user) {

        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<UserVo> userVoList = userMapper.selectUserAll(user);


        List<UserDto> restUserList = new ArrayList<>();
        PageInfo pageInfo = new PageInfo(userVoList);


        for (UserVo userVo : userVoList) {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(userVo, userDto);

            userDto.setDeleteFlag(DeleteFlagEnum.setCodeGetDesc(userVo.getDeleteFlag()));
            userDto.setManagementFlag(ManagementFlagEnum.setCodeGetDesc(userVo.getManagementFlag()));

            restUserList.add(userDto);
        }

        PageInfo pageResult = new PageInfo(restUserList);
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPages(pageInfo.getPages());

        return  pageResult;
    }


    @Override
    public RetResult<String> updateUserByInfo(UserVo userVo, HttpServletRequest request){
        System.out.println("修改............." + request.getSession().getId());
        String  phoneCode = (String)request.getSession().getAttribute("phoneCode");
        if(StringUtils.isEmpty(phoneCode)){
            return RetResponse.makeErrRsp("验证码已失效,请重新发送");
        }
        JSONObject jsonObject = JSON.parseObject(phoneCode);
        if(StringUtils.isNotEmpty(jsonObject.getString("code")) && userVo.getCode().equals(jsonObject.getString("code"))){
            logger.error("验证码校验成功!" + phoneCode);
            request.getSession().removeAttribute("phoneCode");
        }else {
            logger.error("验证码校验失败! phoneCode= " + phoneCode + "user.getCode()" + userVo.getCode());
            return RetResponse.makeErrRsp("验证码校验失败");
        }
        if(StringUtils.isEmpty(userVo.getLoginName())){
            return RetResponse.makeErrRsp("账户为空");
        }
        if(StringUtils.isEmpty(userVo.getLoginPwd())){
            return RetResponse.makeErrRsp("密码为空");
        }
        //MD5进行加密
        userVo.setLoginPwd(Md5Util.md5(userVo.getLoginPwd()));

        try {
            userMapper.updateUserByLoginName(userVo);
            return RetResponse.makeOKRsp("修改成功!");
        } catch (Exception e) {
            throw new RuntimeException("修改数据异常！");
        }
    }

    @Override
    public RetResult<String> registerUserOne(UserVo user, String registration_way, HttpServletRequest request) {

        System.out.println("注册............." + request.getSession().getId());
        String  phoneCode = (String)request.getSession().getAttribute("phoneCode");
        if(StringUtils.isEmpty(phoneCode)){
            return RetResponse.makeErrRsp("验证码已失效,请重新发送");
        }
        JSONObject jsonObject = JSON.parseObject(phoneCode);

        if(StringUtils.isNotEmpty(jsonObject.getString("code")) && user.getCode().equals(jsonObject.getString("code"))){
            logger.error("验证码校验成功!" + phoneCode);
            request.getSession().removeAttribute("phoneCode");
        }else {
            logger.error("验证码校验失败! phoneCode= " + phoneCode + "user.getCode()" + user.getCode());
            return RetResponse.makeErrRsp("验证码校验失败");
        }

        //校验User是否为NULL
        if(null != validUserIsNull(user)){
            return validUserIsNull(user);
        }

        //参数赋值
        giveParameter(user, registration_way);

        try {
            userMapper.insertUserOne(user);
            return RetResponse.makeOKRsp("注册成功!");
        } catch (RuntimeException e) {
            throw new RuntimeException("registerUserOne方法注册失败", e);
        }
    }

    @Override
    public RetResult<String> selectUserByName(String loginName) {
        if(StringUtils.isBlank(loginName)){
            return RetResponse.makeErrRsp("请填写用户名!");
        }
        UserVo user = userMapper.selectUserByLoginName(loginName);
        if(user == null){
            return RetResponse.makeErrRsp("该用户名未注册!");
        }
        return RetResponse.makeOKRsp();
    }

    @Override
    public RetResult<String> loginSelect(UserVo user, HttpServletRequest request,  String registration_way) {

        if(null != validLoginIsNull(user)){
            return validLoginIsNull(user);
        }

        //判断用户是否已经登录过，登录过直接ok
        UserVo sessionUser = (UserVo)request.getSession().getAttribute("user");

        if (sessionUser != null && user.getLoginName().equalsIgnoreCase(sessionUser.getLoginName()) && user.getLoginPwd().equals(sessionUser.getLoginPwd())) {

            return RetResponse.makeOKRsp(JsonUtil.toJSON(sessionUser));
        }

        UserVo loginInfo = userMapper.selectUserByLoginNameAndPwd(user);

        if(null == loginInfo){
            return RetResponse.makeErrRsp("密码错误");
        }

        //erp入口登录
        if(RegistrationWayEnum.COME_ERP.getCode().equals(registration_way)){
            // erp注册 erp登录
            if(RegistrationWayEnum.COME_ERP.getCode().equals(loginInfo.getRegistrationWay())){
                if(ManagementFlagEnum.NOT_MANAGEMENT.getCode().equals(loginInfo.getManagementFlag())){
                    return RetResponse.makeErrRsp("您不是管理员，不能登录后台系统");
                }
            }else {
             //小程序注册 erp登录，直接放行
                //return RetResponse.makeErrRsp("您不是管理员，不能登录后台系统");
            }
        }else {
            //小程序登录
                if(!ManagementFlagEnum.NOT_MANAGEMENT.getCode().equals(loginInfo.getManagementFlag())){
                    return RetResponse.makeErrRsp("该账户是管理员账户,请使用子账户或者个体账户登录");
                }
        }


        request.getSession().setAttribute("user" , loginInfo);
        request.getSession().setMaxInactiveInterval(7*24*60*60);

        return RetResponse.makeOKRsp(JsonUtil.toJSON(loginInfo));
    }

    @Override
    public RetResult<String> updateUserInfo(UserVo user) {
        RetResult<String> retResult = validLoginIsNull(user);
        if(null != retResult){
            return retResult;
        }

        UserVo userVo = userMapper.selectUserById(user.getId());

        //MD5进行加密
        if(StringUtils.isBlank(user.getLoginPwd())){
            user.setLoginPwd(Md5Util.md5(user.getLoginPwd()));
        }

        //交换修改信息
        //userVo.setUsername(user.getUsername());
        userVo.setLoginPwd(user.getLoginPwd());
        //userVo.setPhoneNum(user.getPhoneNum());
//        userVo.setEmail(user.getEmail());

        try {
            int i = userMapper.updateUserInfoById(userVo);
            if(i == 1){
              return   RetResponse.makeOKRsp("修改用户信息成功!");
            }
            return RetResponse.makeErrRsp("修改用户信息失败!");
        } catch (RuntimeException e) {
            throw new RuntimeException("修改用户信息异常!");
        }

    }


    /**
     * 停用账户
     * @param id
     * @return
     */
    @Override
    public RetResult<String> deleteUserInfo(Long id) {

        try {
            userMapper.deleteUserInfoById(id);
            return RetResponse.makeOKRsp("删除账号成功!");
        } catch (RuntimeException e) {
            throw new RuntimeException("删除用户信息异常!");
        }

    }



    /**
     * 给user赋予参数
     * @param user
     */
    private void giveParameter(UserVo user, String registration_way) {

        //是子账号 和 管理员
        if(RegistrationWayEnum.COME_ERP.getCode().equals(registration_way)){
            if(null != user.getId() && 0 != user.getId()){
                user.setChildId(user.getId());
                user.setManagementFlag(ManagementFlagEnum.NOT_MANAGEMENT.getCode());
                user.setId(null);
            }else {
                user.setChildId(null);
                user.setManagementFlag(ManagementFlagEnum.IS_MANAGEMENT.getCode());
                user.setId(null);
            }
        }else {
            user.setManagementFlag(ManagementFlagEnum.NOT_MANAGEMENT.getCode());
        }

        //注册方式
        user.setRegistrationWay(registration_way);

        //MD5进行加密
        user.setLoginPwd(Md5Util.md5(user.getLoginPwd()));
        //是否删除
        user.setDeleteFlag(DeleteFlagEnum.NOT_DELETE.getCode());
    }

    /**
     * 校验参数是否为空，格式是否正确
     * @param user
     * @return
     */
    private RetResult<String> validUserIsNull(UserVo user) {

        //验证码是否一致


        if(null == user){
            return RetResponse.makeErrRsp("注册信息不存在,请检查重新填写");
        }
//        if(StringUtils.isEmpty(user.getUsername())){
//            return RetResponse.makeErrRsp("注册昵称为空，请检查重新填写");
//        }
        if(StringUtils.isEmpty(user.getLoginName())){
            return RetResponse.makeErrRsp("注册用户名为空，请检查重新填写");
        }else {
            //校验用户名为手机号码
          if(!MathUtils.validateMobilePhone(user.getLoginName())){
              return RetResponse.makeErrRsp("账号(手机号码)格式不正常");
          }
        }

        if(StringUtils.isEmpty(user.getLoginPwd())){
            return RetResponse.makeErrRsp("注册密码为空，请检查重新填写");
        }
//        if(StringUtils.isEmpty(user.getPhoneNum())){
//            return RetResponse.makeErrRsp("注册手机号码为空，请检查重新填写");
//        }
//        if(StringUtils.isEmpty(user.getEmail())){
//            return RetResponse.makeErrRsp("注册邮箱为空，请检查重新填写");
//        }

        user.setLoginName(user.getLoginName().trim());

        user.setLoginPwd(user.getLoginPwd().trim());

        if(null != userMapper.selectUserByLoginName(user.getLoginName())){
            return RetResponse.makeErrRsp("用户名已存在，请重新填写");
        }

        if(null != user.getId()){
            UserVo info = userMapper.selectUserById(user.getId());
            //如果是个体户，不让注册
            if(null != info && null != info.getRegistrationWay() && info.getRegistrationWay() != "" ){
                if(RegistrationWayEnum.COME_ANDROID.getCode().equals(info.getRegistrationWay())){
                    return RetResponse.makeErrRsp("个体户不能注册子账户!");
                }
            }
        }


        return null;
    }


    /**
     * 校验参数是否为空，格式是否正确
     * @param user
     * @return
     */
    private RetResult<String> validLoginIsNull(UserVo user) {
        if(null == user){
            return RetResponse.makeErrRsp("登录信息不存在,请检查重新填写");
        }

        if(StringUtils.isEmpty(user.getLoginName())){
            return RetResponse.makeErrRsp("登录用户名为空，请检查重新填写");
        }
        if(StringUtils.isEmpty(user.getLoginPwd())){
            return RetResponse.makeErrRsp("登录密码为空，请检查重新填写");
        }

        user.setLoginName(user.getLoginName().trim());

        user.setLoginPwd(user.getLoginPwd().trim());



        //登录需要判断，用户名是否存在
        if(MathUtils.isNullOrZero(user.getId())){
            if(null == userMapper.selectUserByLoginName(user.getLoginName())){
                return RetResponse.makeErrRsp("用户名不存在，请重新填写");
            }
        }else {
            //修改需要判断 id是否为当前用户名
            if(userMapper.selectUserByLoginNameAndId(user.getLoginName(), user.getId()) != 1){
                return RetResponse.makeOKRsp("不能修改账号!");
            }
        }

        user.setLoginPwd(Md5Util.md5(user.getLoginPwd()));

        return null;
    }



}
